using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OA.BLL
{
    public class Mail
    {
        #region 发送邮件

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="subject">标题</param>
        /// <param name="body">内容</param>
        /// <param name="tos">邮件地址;邮件地址</param>
        /// <returns></returns>
        public static Common.Result SendMail(string subject, string body, string tos)
        {
            return SendMail(subject, body, tos.Split(';'), null, null,null);
        }

        public static Common.Result SendMail(string subject, string body, string[] tos)
        {
            return SendMail(subject, body, tos, null, null,null);
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="subject">邮件标题</param>
        /// <param name="body">内容</param>
        /// <param name="tos">接收者 格式 test@test.com 或 姓名:test@test.com</param>
        /// <param name="ccs">抄送者 格式 test@test.com 或 姓名:test@test.com</param>
        /// <param name="bccs">密送者 格式 test@test.com 或 姓名:test@test.com</param>
        /// <returns></returns>
        public static OA.Common.Result SendMail(string subject, string body, string[] tos, string[] ccs, string[] bccs,Model.Config.MailConfig config)
        {
            OA.Common.Result ret = new OA.Common.Result();
           /* try
            {*/
            if (config == null) config = SystemConfig.LoadConfig().Mail;
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(config.SMTPServer, config.SMTPPort);
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new System.Net.NetworkCredential(config.UserName, config.Password);
                smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.SubjectEncoding = System.Text.Encoding.UTF8;
                message.IsBodyHtml = true;
                message.From = new System.Net.Mail.MailAddress(config.From, config.NickName);
                message.Subject = subject;
                message.Body = body;
                foreach (var to in tos)
                {
                    var tt = to.Split(':');
                    if (tt.Length > 1)
                    {
                        message.To.Add(new System.Net.Mail.MailAddress(tt[1], tt[0]));
                    }
                    else
                    {
                        message.To.Add(tt[0]);
                    }
                }
                if (ccs != null)
                {
                    foreach (var to in ccs)
                    {
                        var tt = to.Split(':');
                        if (tt.Length > 1)
                        {
                            message.CC.Add(new System.Net.Mail.MailAddress(tt[1], tt[0]));
                        }
                        else
                        {
                            message.CC.Add(tt[0]);
                        }
                    }
                }
                if (bccs != null)
                {
                    foreach (var to in bccs)
                    {
                        var tt = to.Split(':');
                        if (tt.Length > 1)
                        {
                            message.Bcc.Add(new System.Net.Mail.MailAddress(tt[1], tt[0]));
                        }
                        else
                        {
                            message.Bcc.Add(tt[0]);
                        }
                    }
                }
                smtp.Send(message);
                ret.success = true;
                ret.message = "发送成功";
                /*
            }
            catch(Exception e)
            {
                throw e;
                ret.success = false;
                ret.message = e.Message;
            }*/
            return ret;
        }
        #endregion

        #region 事件邮件模板通知

        /// <summary>
        /// 发送邮件通知
        /// </summary>
        /// <param name="EventCode">事件编号</param>
        /// <param name="MailCode">邮件模板编号</param>
        /// <param name="variableNames">变量名称集合，以,逗号分隔</param>
        /// <param name="variables">变量集合</param>
        public static Common.Result MailNotifyByEvent(string EventCode, string MailCode, string strVariableNames, params object[] variables)
        {
            return MailNotifyByEvent(EventCode,null, MailCode, strVariableNames, variables);
        }
        /// <summary>
        /// 发送邮件通知
        /// </summary>
        /// <param name="EventCode">事件编号</param>
        /// <param name="mailaddress">附加的接收人</param>
        /// <param name="MailCode">邮件模板编号</param>
        /// <param name="variableNames">变量名称集合，以,逗号分隔</param>
        /// <param name="variables">变量集合</param>
        /// <returns></returns>
        public static Common.Result MailNotifyByEvent(string EventCode, string mailaddress, string MailCode, string strVariableNames, params object[] variables)
        {
            Common.Result ret = new Common.Result(false, 0, "发送失败");
            var events = new Events().Get(EventCode);
            if (events == null)
            {
                ret.message = "事件编号不存在";
                return ret;
            }

            string tos = "";
            if (events.Notifys.Count > 0)
            {
                foreach (var u in events.Notifys)
                {
                    tos += ";" + u.Manager.RealName + ":" + u.Manager.Email;
                }
                tos=tos.Substring(1);
            }
            if (!string.IsNullOrEmpty(mailaddress)) tos += ";" + mailaddress;
            ret = MailNotify(tos, MailCode, strVariableNames, variables);
            return ret;
        }

        public static Common.Result MailNotify(string mailaddress, string MailCode, string strVariableNames, params object[] variables)
        {
            return MailNotify(mailaddress.Split(';'), MailCode, strVariableNames, variables);
        }

        public static Common.Result MailNotify(Model.Config.MailConfig config, string mailaddress, string MailCode, string strVariableNames, params object[] variables)
        {
            return MailNotify(config,mailaddress.Split(';'), MailCode, strVariableNames, variables);
        }

        /// <summary>
        /// 发送邮件通知
        /// </summary>
        /// <param name="mailaddress">邮件地址</param>
        /// <param name="MailCode">邮件模板编号</param>
        /// <param name="variableNames">变量名称集合，以,逗号分隔</param>
        /// <param name="variables">变量集合</param>
        /// <returns></returns>
        public static Common.Result MailNotify( string[] mailaddress, string MailCode, string strVariableNames, params object[] variables)
        {
            return MailNotify(null, mailaddress, MailCode, strVariableNames, variables);
        }

        /// <summary>
        /// 发送邮件通知
        /// </summary>
        /// <param name="mailaddress">邮件地址</param>
        /// <param name="MailCode">邮件模板编号</param>
        /// <param name="variableNames">变量名称集合，以,逗号分隔</param>
        /// <param name="variables">变量集合</param>
        /// <returns></returns>
        public static Common.Result MailNotify(Model.Config.MailConfig config, string[] mailaddress, string MailCode, string strVariableNames, params object[] variables)
        {
            Common.Result ret = new Common.Result(false, 0, "发送失败");
            var mail = new MailTemplate().Get(MailCode);
            if (mail == null)
            {
                ret.message = "邮件编号(" + MailCode + ")不存在";
                return ret;
            }
            Activa.LazyParser.CSharpContext context = new Activa.LazyParser.CSharpContext();
            if (!string.IsNullOrEmpty(strVariableNames))
            {
                var VariableNames = strVariableNames.Split(',');
                for (int i = 0; i < VariableNames.Length; i++)
                {
                    context.Set(VariableNames[i], variables[i]);
                }
            }
            var velocityParser = new Activa.SharpTemplate.SharpTemplate<Activa.SharpTemplate.Config.Velocity>();
            string bodykey = Common.Keys.MailTemplateBody + mail.Code;
            var bodypreParse = Common.CacheHelper.Get<Activa.SharpTemplate.PreParsedTemplate>(bodykey);
            if (bodypreParse == null)
            {
                bodypreParse = velocityParser.Parse(mail.Body);
                Common.CacheHelper.Insert(bodykey, bodypreParse);
            }
            var body = velocityParser.Render(bodypreParse, context);
            string subjectkey = Common.Keys.MailTemplateSubject + mail.Code;
            var subjectprParse = Common.CacheHelper.Get<Activa.SharpTemplate.PreParsedTemplate>(subjectkey);
            if (subjectprParse == null)
            {
                subjectprParse = velocityParser.Parse(mail.Subject);
                Common.CacheHelper.Insert(subjectkey, subjectprParse);
            }
            var subject = velocityParser.Render(subjectprParse, context);

            ret = Mail.SendMail(subject, body, mailaddress,null,null,config);
            return ret;
        }


        #endregion
    }
}
